package com.xt.mvcpilot.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import com.xt.mvcpilot.AppConstants;
import com.xt.mvcpilot.data.User;

/**
 * 
 * 
 * @author xiaotao
 * @version 2011-12-29
 *
 */
@Controller
@Scope("prototype")
public class AccessController extends AppBasicController{
	
	protected final Logger log = LoggerFactory.getLogger(getClass());
	
	
	/**
	 * index page
	 * 
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {

		return AppConstants.INDEX_VIEW;
	}
	

	/**
	 * login form
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {

		return AppConstants.LOGIN_VIEW;
	}

	
	/**
	* Returns the domain User object for the currently logged in user, or null
	* if no User is logged in.
	* 
	* @return User object for the currently logged in user, or null if no User
	*         is logged in.
	*/
	//final HttpServletRequest request, Principal principal
	@ModelAttribute("user")
	public User getCurrentUser(final HttpServletRequest request) {
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth == null)
			return null;
		
	    Object principal = auth.getPrincipal();

	    if (principal instanceof User) return ((User) principal);
	    request.getSession().setAttribute("", (User) principal);
	    
	    // principal object is either null or represents anonymous user -
	    // neither of which our domain User object can represent - so return null
	    return null;
	}

}
